import os.path
import sys

import win32api
import win32con
import win32event
import winerror
from PySide2 import QtWidgets, QtCore, QtGui
from PySide2.QtWidgets import QDesktopWidget

from utils.file_utils import Config

sys.path.append(os.path.abspath('ui'))
sys.path.append(os.path.abspath('ui/images'))
sys.path.append(os.path.abspath('resource'))

from ui.main_window import Ui_MainWindow
from utils.task import QTask
from pages.tab_widget.dichotomy import Dichotomy
from pages.tab_widget.upgrade import Upgrade
from pages.tab_widget.autotest import AutoTest
from pages.dialog.settings import Settings

VERSION = ' V3.2.0'


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    LIGHT_ON = 'background-color: rgb(0, 255, 0);border-radius:8px;'
    LIGHT_OFF = 'background-color: rgb(0, 128, 0);border-radius:8px;'

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        QtWidgets.QApplication.setStyle('Fusion')
        self.setWindowTitle(self.windowTitle() + VERSION)

        self.devices = []
        self.running = False
        self.settings_dialog = Settings(self)

        self.upgrade_widget = Upgrade(self)
        self.dichotomy_widget = Dichotomy(self)
        self.autotest_widget = AutoTest(self)

        self.verticalLayoutUpgrade.addWidget(self.upgrade_widget)
        self.verticalLayoutDichotomy.addWidget(self.dichotomy_widget)
        self.verticalLayoutAutoTest.addWidget(self.autotest_widget)

        self.pushButtonSettings.clicked.connect(self.show_settings_dialog)
        self.pushButtonRefresh.clicked.connect(self.refresh_device)
        self.pushButtonRun.clicked.connect(self.start_task)

        self.make_tmp_dir()
        self.task = QTask()
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.light_blinking)
        self.refresh_device()

    def show_settings_dialog(self):
        self.settings_dialog.reload_settings()
        self.settings_dialog.exec_()

    def make_tmp_dir(self):
        if not os.path.exists(Config.CONFIG_PATH):
            if os.path.exists('D:'):
                dayu200_path = r'D:\blue_caches\rk_images'
                sdk_path = r'D:\blue_caches\sdk_pkgs'
            else:
                dayu200_path = r'C:\blue_caches\rk_images'
                sdk_path = r'C:\blue_caches\sdk_pkgs'
            os.makedirs(dayu200_path, exist_ok=True)
            os.makedirs(sdk_path, exist_ok=True)
            config_data = {
                'dayu200_path': dayu200_path,
                'sdk_path': sdk_path,
                'ide_path': '',
            }
            Config.save_config(config_data)
        else:
            config_data = Config.read_config()
            dayu200_path = config_data.get('dayu200_path')
            sdk_path = config_data.get('sdk_path')
            if dayu200_path:
                os.makedirs(dayu200_path, exist_ok=True)
            if sdk_path:
                os.makedirs(sdk_path, exist_ok=True)

    def refresh_device(self):
        self.devices = self.task.list_device()
        self.statusbar.showMessage('发现 {} 台RK3568设备'.format(len(self.devices)), 2000)

    def start_task(self):
        if self.running:
            return
        if self.tabWidget.currentWidget() == self.tabUpgrade:
            self.upgrade_widget.start_task()
        elif self.tabWidget.currentWidget() == self.tabDichotomy:
            self.dichotomy_widget.start_task()
        else:
            self.autotest_widget.start_task()

    def enter_busy(self):
        self.running = True
        self.pushButtonRefresh.setEnabled(False)
        self.pushButtonRun.setEnabled(False)
        icon = QtGui.QIcon()
        icon.addFile(u":/images/running.png", QtCore.QSize(), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButtonRun.setIcon(icon)
        self.pushButtonRun.setText('运行中')
        self.timer.start(300)

    def exit_busy(self):
        self.running = False
        self.pushButtonRefresh.setEnabled(True)
        self.pushButtonRun.setEnabled(True)
        icon = QtGui.QIcon()
        icon.addFile(u":/images/start.png", QtCore.QSize(), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButtonRun.setIcon(icon)
        self.pushButtonRun.setText(' 开始')
        self.statusbar.clearMessage()
        self.labelLight.setStyleSheet(self.LIGHT_OFF)
        self.timer.stop()

    def light_blinking(self):
        if self.labelLight.styleSheet() == self.LIGHT_OFF:
            self.labelLight.setStyleSheet(self.LIGHT_ON)
        else:
            self.labelLight.setStyleSheet(self.LIGHT_OFF)


if __name__ == '__main__':
    mutex = win32event.CreateMutex(None, True, 'BlueTool.exe')
    if not mutex:
        win32api.MessageBox(None, '启动失败', '提示', win32con.MB_OK)
        sys.exit(0)
    if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS:
        win32api.MessageBox(None, '工具已启动', '提示', win32con.MB_OK)
        sys.exit(0)
    app = QtWidgets.QApplication(sys.argv)
    win = MainWindow()

    # 居中显示
    screen = QDesktopWidget().screenGeometry(0)
    win_size = win.geometry()
    win.move((screen.width() - win_size.width()) // 2, (screen.height() - win_size.height()) // 2 - 20)
    win.show()
    # win.showMaximized()
    sys.exit(app.exec_())
